A r t i c l e s
Navigation

Note: This site is
a bit older, personal views
may have changed.

M a i n P a g e

D i r e c t o r y

Returning Pointer or Object As Function Result


Returning pointers as function results or objects as function results can sometimes be confusing... since the programmer can be unclear about what is a valid pointer or what is a valid object to return.

Can a local pointer be returned safely.. and can a local object be returned safely.. may be the most confusing to some who are afraid of scope problems and invalid pointers or invalid references.

function something: TXyzObject;
var tmp: TXyzObject;
begin
  tmp:= TXyzObject.create;
  result:= tmp; 
end;
Above is a a valid object is then returned. Just remember that the object must be freed later, so write documentation stating so.. or name the function clearly such as CreateObject.

Similar rules apply when using the 'result' variable more directly:

function something: TXyzObject;
begin
  result:=TXyzObject.create;
end; 
Above is fine, but if you ever leave out the 'create' then you have no object, only an invalid pointer.

What about pointers or pointers to records for example:

function something: PXyzRecord;
var tmp: PXyzRecord;
begin
  new(tmp);
  result:= tmp; 
end;
Above is a a valid record on the heap that returned. Just remember that the record must be freed later, so write documentation stating so.. or name the function clearly such as CreateXyzRecord along with FreeXyzRecord. Or OpenConnect CloseConnection.. in other words use similar pairs of matching functions so the person knows they must free and create, or open and close, or init and fini.

How about using the result variable more directly:

function something: PXyzRecord;
begin
  new(result)
end; 
Above is fine, but if you ever leave out the 'new()' then you have an invalid pointer.

About
This site is about programming and other things.
_ _ _